package com.niezhipeng.routing;

import com.niezhipeng.utils.ConnectFactoryUtils;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

public class ReceiveLogsDirect {

    private static final String EXCHANGE_NAME = "direct_logs";
    private static final String[] ROUTE_KEYS = {"info", "error"};

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        ConnectFactoryUtils.setFactoryConfig(factory);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 直接模式，该模式主要是利用路由键（routing key），交换机通过该键将信息放入对应的队列中
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        // info日志队列
        // 随机生成一个临时队列
        String queueNameInfo = channel.queueDeclare().getQueue();
        // 绑定此队列,info队列同时接受info和error信息
        channel.queueBind(queueNameInfo, EXCHANGE_NAME, "info");
        channel.queueBind(queueNameInfo, EXCHANGE_NAME, "error");

        DeliverCallback deliverCallbackInfo = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Info队列接收到消息 '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueNameInfo, true, deliverCallbackInfo, consumerTag -> {
        });

        // error日志队列
        // 随机生成一个临时队列
        String queueNameError = channel.queueDeclare().getQueue();
        // 绑定
        channel.queueBind(queueNameError, EXCHANGE_NAME, "error");
        // 回调对象
        DeliverCallback deliverCallbackError = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Error队列接收到消息 '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueNameError, true, deliverCallbackError, consumerTag -> {
        });

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    }
}

